
import {useContext,useRef,useEffect,useState} from "react"
import {GolBalContext} from "@/redux/index"
import {changeCount} from '@/redux/action'
import "./index.less"
import { Row, Col , Typography , Tabs , Form, Input, Button, Checkbox ,message  } from 'antd';
import { UserOutlined, LockOutlined , WhatsAppOutlined , MobileOutlined,PhoneOutlined , AppstoreOutlined  } from '@ant-design/icons';
import {Link} from "umi"
import {reg} from "@/utils/validate"
import {ajax} from "@/services"
import {history} from "umi"
const {Title } =Typography 
const { TabPane } = Tabs;
export default function LoginPage(props){
  const {state,dispatch} =  useContext(GolBalContext)
  console.log(props)
  return (
    <div className="login">
        <video 
          className="myvideo" 
          id="myvideo" 
          autoPlay  
          loop  
          playsInline
          muted
          src="http://47.104.209.44/mp/brkw.mp4"
        ></video>
        <Row >
            <Col className="login-box" xs={22} sm={18} md={12} lg={10} xl={6} xxl={4} >
                <Title className="title">千锋武汉HTML5教学管理系统</Title>   
                <Tabs defaultActiveKey="1" >
                  <TabPane tab="账号密码登录" key="1">
                      <LogigByPass location={props.location } ></LogigByPass>
                  </TabPane>
                  <TabPane tab="验证号码登录" key="2">
                      <LoginByCode></LoginByCode>
                  </TabPane>
                </Tabs>
            </Col>
        </Row>
    </div>
  )
}

const layout = {
  labelCol:{
    span:4,
    offset:1,
  },
  wrapperCol:{
    span:18,
    offset:1
  }
}
const tailLayout = {
  wrapperCol:{
      span:18,
      offset:6
  }
}
function LogigByPass({location}){
   
    useEffect(()=>{
      console.log(form)
      if(localStorage.getItem("remember")){
        form.current.setFieldsValue({
          "password":localStorage.getItem("thispass")
        })
      }

      if(localStorage.getItem("account")){
        form.current.setFieldsValue({
          "account":localStorage.getItem("account")
        })
      }

      // console.log(location)  注册的时候把手机号码带过来 
      if(location.query.phone){
        form.current.setFieldsValue({
          "account":location.query.phone,
          "password":''
        })
      }
    },[])

    const onFinish = async (value)=>{
        let res = await ajax.login(value)
        const {code,result,token } = res;
        if(code==200){
          localStorage.setItem("account",value.account)
          sessionStorage.setItem("authtoken",token)
          if(value.remember){
            localStorage.setItem("thispass",value.password)
            localStorage.setItem("remember",'true')
          }else{
            localStorage.removeItem("remember")
            localStorage.removeItem("thispass")
          } 
          history.push("/main/home")
        }
    }
    const onFinishFailed = ()=>{
      message.error("请输入有效的登录信息")
    }
    const form:any = useRef()
    return (
      <div>
          <Form
               name="basic"
               initialValues={{ remember: true }}
               onFinish={onFinish}
               onFinishFailed={onFinishFailed}
               autoComplete="off"
               className="login-form"
               ref={form}
               {...layout}
          >
            <Form.Item
                label="账号"
                name="account"
                rules={[{ required: true, message: '请输入你的账号' }]}
              >
                <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="账号(手机号或者用户名)" />
            </Form.Item>

            <Form.Item
                label="密码"
                name="password"
                rules={[
                  { required: true, message: '请输入你的密码' },
                  {
                    pattern:reg.pwd,
                    message:"请输入6-16位的数字和字母组合"
                  }
                ]}
              >
                <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} placeholder="密码(6-16位数字+字母)" />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住密码</Checkbox>
              </Form.Item>
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" block htmlType="submit" className="login-form-button">
                登录
              </Button>
            </Form.Item>
            <Form.Item className="links" {...tailLayout} style={{display:'flex',justifyContent:'space-between'}}>
                <Link style={{color:"#f50",fontSize:13}} to="/register">没有账号,立即注册</Link>
                <Link style={{color:"#999",fontSize:13}} to="/forgetpass">忘记密码</Link>
            </Form.Item>
          </Form>
      </div>
    )
}

const layout1 = {
  labelCol:{
    span:6,
    offset:1,
  },
  wrapperCol:{
    span:17,
  }
}
const tailLayout1 = {
  wrapperCol:{
      span:17,
      offset:7
  }
}
const CountNum = 120;
function LoginByCode(){
  const [flag,setFlag] = useState<boolean>(false);
  const [toggle,setToggle] = useState<boolean>(true);
  let  [count,setCount] = useState<number>(CountNum)

  useEffect(()=>{
    if(localStorage.getItem("phone")){
      form.current.setFieldsValue({
        "phone":localStorage.getItem("phone")
      })
    }
  },[])
  async function  onFinish(value){
      let res=  await ajax.verifyCode(value)
      const {code,result,token} = res;
      if(code==200){
        localStorage.setItem("phone",value.phone)
        sessionStorage.setItem("authtoken",token)
        history.push("/main/home")
      }
  }
  function onFinishFailed(){
      message.error("请输入有效的登录信息")
  }
  const form:any = useRef()
  const phoneEle:any = useRef()
  const checkPhoneFlag = ()=>{
      console.log(form)
      console.log(phoneEle)
      var phoneValue = phoneEle.current.state.value 
      var value = form.current.getFieldValue("phone")
      if(reg.phone.test(value)){
        setFlag(true)
      }else{
        setFlag(false)
      }
  }
  const clickToSend = ()=>{
      sendCodeAction()
      count = count -1
      setCount(count);
      setToggle(false);
      var timer = setInterval(()=>{
          if(count>0){
            count = count -1
            setCount(count);
            setToggle(false);
          }else{
            clearInterval(timer)
            setToggle(true);
            setCount(CountNum);
          }
      },1000)
  }

  const sendCodeAction = async ()=>{
    var phone = form.current.getFieldValue("phone")
    let res = await ajax.sendCode({phone})
  }
  return (
    <div>
        <Form
            name="basic"
            initialValues={{ }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
            className="login-form"
            ref={form}
            {...layout1}
          >
            <Form.Item
                label="手机号码"
                name="phone"
                rules={[
                  { required: true, message: '请输入手机号码' },
                  {pattern:reg.phone,message:"请输入正确的手机号码"}
                ]}
              >
                <Input ref={phoneEle} onChange={checkPhoneFlag} prefix={<PhoneOutlined  className="site-form-item-icon" />} placeholder="请输入手机号码" />
            </Form.Item>

            <Form.Item
                label="验证号码"
                name="captcha"
                rules={[
                  { required: true, message: '请输入验证号码' },
                  { pattern:/^\d{4}$/,message:"请输入4位验证码"}
                ]}
              >
                <Row>
                  <Col span={13}>
                    <Input prefix={<AppstoreOutlined className="site-form-item-icon" />} placeholder="请输入验证号码" />
                  </Col>
                  <Col span={10} offset={1}>
                      {toggle?  <Button  type="primary" onClick={clickToSend} >点击发送</Button> 
                        : <Button disabled type="primary" >剩余 {count} S</Button> 
                      }
                  </Col>
                </Row>
            </Form.Item>
            <Form.Item {...tailLayout1}>
              <Button type="primary"  block htmlType="submit" className="login-form-button">
                立即登录
              </Button>
            </Form.Item>
            <Form.Item className="links" {...tailLayout1} style={{display:'flex',justifyContent:'space-between'}}>
                <Link style={{color:"#f50",fontSize:13}} to="/register">没有账号,立即注册</Link>
                <Link style={{color:"#999",fontSize:13}} to="/forgetpass">忘记密码</Link>
            </Form.Item>
          </Form>
    </div>
  )
}